package axdoc.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import axdoc.dao.base.BusinessEventUtil;
import axdoc.dao.base.BusinessTypeConfig;
import axdoc.dao.base.EventType;
import axdoc.model.CommonActivity;
import axdoc.model.SelectValue;
import axdoc.service.CommonActivityService;

@Controller
@RequestMapping("activity")
public class ActivityController {

	private static Logger logger = LoggerFactory.getLogger(ActivityController.class);

	@Autowired
	BusinessEventUtil businessEventUtil;
	@Autowired
	CommonActivityService commonActivityService;

	@RequestMapping(value = "list")
	public String list() {
		return "activitylist";
	}

	@RequestMapping(value = "json")
	@ResponseBody
	public String json() {
		return JSON.toJSONString(commonActivityService.query());
	}

	@RequestMapping(value = "menus")
	@ResponseBody
	public String menus() {
		List<BusinessTypeConfig> list = BusinessEventUtil.businessTypes;
		List<SelectValue> rules = new ArrayList<SelectValue>();
		if (list != null && list.size() > 0) {
			int i = 0;
			for (BusinessTypeConfig t : list) {
				SelectValue sv = new SelectValue();
				sv.setId(String.valueOf(t.getBusinessId()));
				sv.setName(t.getBusinessName());
				if (i == 0) {
					sv.setSelected(true);
				}
				rules.add(sv);
				i++;
			}
		}
		return JSON.toJSONString(rules);
	}

	@RequestMapping(value = "events/{businessId}")
	@ResponseBody
	public String events(@PathVariable("businessId") int businessId) {
		List<EventType> list = businessEventUtil.getEventTypes(businessId);
		List<SelectValue> rules = new ArrayList<SelectValue>();
		if (list != null && list.size() > 0) {
			int i = 0;
			for (EventType t : list) {
				SelectValue sv = new SelectValue();
				sv.setId(String.valueOf(t.getEventType()));
				sv.setName(t.getEventName());
				if (i == 0) {
					sv.setSelected(true);
				}
				rules.add(sv);
				i++;
			}
		}
		return JSON.toJSONString(rules);
	}

	@RequestMapping(value = "add")
	public ModelAndView addAct(ModelAndView model) {
		model.addObject("act", new CommonActivity());
		model.setViewName("activity");
		model.addObject("action", "addAct");
		return model;
	}

	@RequestMapping(value = "addAct")
	@ResponseBody
	public String addAct(CommonActivity act) {
		int res = commonActivityService.addAct(act);
		logger.info("[添加活动][" + act.toString() + "][res:" + res + "]");
		return "success";

	}

}
